<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/20
 * Time: 17:17
 */

namespace zhtfrontend\controllers;

use common\components\actions\DeleteAction;
use common\components\helpers\Fun;
use common\components\helpers\Tree;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;
use zhtfrontend\components\bases\BaseController;
use zhtfrontend\models\datas\Headmaster;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\forms\HeadmasterSearchForm;
use yii\data\Pagination;

class HeadmasterController extends BaseController
{
    //班主任列表
    public function actionIndex()
    {
        $mids = Fun::getMechanicIds();
        $search_form = new HeadmasterSearchForm();
        if (\Yii::$app->request->isPost) {
            $search_form->load(\Yii::$app->request->post());
        }
        $search_data = array_filter($search_form->attributes);
        $headmaster = Headmaster::find()->where(['status' => 1])->orderBy('mechanic_id ASC');
        if (!empty($search_data['name'])) {
            $headmaster->andWhere(['like', 'name', $search_data['name']]);
        }
        if (!empty($search_data['tel'])) {
            $headmaster->andWhere(['like', 'mobile', $search_data['tel']]);
        }
        if (!empty($search_data['mechanic_name'])) {
            $ids = Mechanic::find()->select('id')->where(['like','name',$search_data['mechanic_name']])->column();
            $headmaster->andWhere(['mechanic_id'=>$ids]);
        }
        if ($mids) {
            $headmaster->andWhere(['mechanic_id' => $mids]);
        }
        $pages = new Pagination(['totalCount' => $headmaster->count(), 'pageSize' => 14, 'params' => array_merge($_GET, $search_data)]);
        $headmaster = $headmaster->offset($pages->offset)->limit($pages->limit)->all();
        $model = Fun::asArray($headmaster, ['mechanic_name', 'deleteHandle']);
        return $this->render('index', ['model' => $model, 'form' => $search_form, 'pages' => $pages]);
    }

    public function actionCreate()
    {
        $mids = Fun::getMechanicIds(); //获取机构以及子机构id
        $model = new Headmaster();
        //$model->scenario = 'create';
        $model->status = 1;
        $mechanicModel = Mechanic::find()->where(['site_id' => Fun::getSiteId(), 'is_delete' => 0, 'status' => 1]);
        if (!empty($mids)) {
            $mechanicModel->andWhere(['id' => $mids]);//这个地方是如果是有机构id传过来，那么可以选择的有当前的机构或者是找个机构的子类
        }
        $mechanic = $mechanicModel->indexBy('id')->all();
        if (count($mechanic) == 1) {
            foreach ($mechanic as $key => $val) {
                $model->mechanic_id = $key;
            }
            $tree_mechanic = ArrayHelper::map($mechanic, 'id', 'name');
        } else {
            $tree_mechanic = (new Tree($mechanic))->get_tree_select();
        }
        $now_year = (int)date('Y');
        $oldyear = $now_year - 100;
        $years = range($oldyear, $now_year);
        $year = [];
        foreach ($years as $y) {
            $year[$y] = $y;
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->account = $model->mobile . '_h';
            if ($model->save(false)) {
                return $this->redirectMessage('添加成功', Fun::url(['headmaster/index']));
            }
        }
        return $this->render('create', ['model' => $model, 'mechanic' => $tree_mechanic, 'year' => $year]);
    }

    public function actionUpdate()
    {
        $id = \Yii::$app->request->get('id');
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = Headmaster::findOne($id);
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $mids = Fun::getMechanicIds(); //获取机构以及子机构id
        $mechanicModel = Mechanic::find()->where(['site_id' => Fun::getSiteId(), 'is_delete' => 0, 'status' => 1]);
        if (!empty($mids)) {
            $mechanicModel->andWhere(['id' => $mids]);
        }
        $mechanic = $mechanicModel->indexBy('id')->all();
        $tree_mechanic = (new Tree($mechanic))->get_tree_select();
        $now_year = (int)date('Y');
        $oldyear = $now_year - 100;
        $years = range($oldyear, $now_year);
        $year = [];
        foreach ($years as $y) {
            $year[$y] = $y;
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->account = $model->mobile . '_h';
            if ($model->save(false)) {
                return $this->redirectMessage('修改成功', Fun::url(['headmaster/index']));
            }
        }
        return $this->render('create', ['model' => $model, 'mechanic' => $tree_mechanic, 'year' => $year]);
    }

    public function actions()
    {
        return [
            'delete' => [
                'class' => DeleteAction::className(),
                'modelClass' => Headmaster::className(),
                'message' => ['success' => '删除成功！'],
                'redirectTo' => 'headmaster/index',
            ],
        ];
    }

}